from django.http import JsonResponse
from django.contrib.auth import authenticate, login, logout
import json

# Create your views here.
def sign_handle(request):
    request.params = json.loads(request.body)
    action = request.params.get('action')
    if action == 'signin':
        return signin(request)
    elif action == 'signout':
        return signout(request)
    else:
        return JsonResponse({'ret': 1, 'msg': '请求错误'}, json_dumps_params={'ensure_ascii': False})

# 登录
def signin(request):
    userName = request.params.get('username')
    passWord = request.params.get('password')
    # 使用 Django auth 库里面的方法校验用户名、密码
    user = authenticate(username=userName, password=passWord)
    # 如果用户名、密码校验失败
    if not user:
        return JsonResponse({'ret': 1, 'msg': '用户名或密码错误'}, json_dumps_params={'ensure_ascii': False})
    # auth_user表中有个字段【is_active】，值为1或0
    if not user.is_active:
        return JsonResponse({'ret': 1, 'msg': '用户已禁用'}, json_dumps_params={'ensure_ascii': False})

    login(request, user)
    return JsonResponse(
        {
            "ret": 0,
            "usertype": user.usertype,
            "userid": user.id,
            "realname": user.realname,
        }, json_dumps_params={'ensure_ascii': False})


# 登出
def signout(request):
    logout(request)
    return JsonResponse({'ret': 0})

